package com.frxuexi.apps

import android.util.Log
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import coil3.compose.AsyncImage
import com.frxuexi.apps.entity.Apps
import com.frxuexi.apps.entity.AppsData
import com.frxuexi.lib_base.BaseTitle
import com.frxuexi.lib_base.UiState
import kotlinx.coroutines.launch

@Composable
fun AppsPage(navHostController: NavHostController,vm:AppsViewModel= hiltViewModel()) {
    var list = remember {
        SnapshotStateList<AppsData>()
    }
    LaunchedEffect(Unit){
        launch {
            vm.state.collect{
                when(it){
                    is UiState.onSuccess<*> ->{
                        Log.i("===",it.data.toString())
                        list.addAll(it.data as Collection<AppsData>)
                    }
                    is UiState.onError->{
                        Log.i("===",it.msg)
                    }

                    else -> {}
                }
            }
        }
        vm.sendIntent(AppIntent.getApps(mapOf("userId" to 1,"page" to 1)))
    }

    Column(Modifier.padding(20.dp)) {
        BaseTitle(navHostController,title = "在线应用")
        list.forEach {
            Spacer(modifier = Modifier.height(10.dp))
            Text(text = it.title)
            LazyVerticalGrid(verticalArrangement = Arrangement.spacedBy(6.dp), columns = GridCells.Fixed(3), content = {
                items(it.appsList){
                    AppsItem(entity = it)
                }
            })
        }
    }

}

@Composable
fun AppsItem(entity:Apps){
    Column(horizontalAlignment = Alignment.CenterHorizontally) {
        AsyncImage(model = entity.appIcon, contentDescription = "", modifier = Modifier.size(40.dp))
        Text(text = entity.appName)
    }
}